package routes

import (
	"context"
	"encoding/json"
	"net/http"
	"time"

	"github.com/gorilla/mux"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"

	"example/game/config"
)

type User struct {
	Name     string    `bson:"name"`
	Coins    int       `bson:"coins"`
	LastTime time.Time `bson:"lastTime"`
}

func GetCoinsHandler(w http.ResponseWriter, r *http.Request) {
	username := r.URL.Query().Get("user")

	// 连接 MongoDB
	clientOptions := options.Client().ApplyURI(config.MongoDBURL)
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}
	defer client.Disconnect(context.TODO())

	// 获取用户集合
	collection := client.Database("game_dev").Collection("users")

	// 查询用户
	filter := bson.M{"name": username}
	var user User
	err = collection.FindOne(context.TODO(), filter).Decode(&user)
	if err != nil {
		if err == mongo.ErrNoDocuments {
			// 创建新用户
			user = User{
				Name:     username,
				Coins:    0,
				LastTime: time.Now(),
			}
			_, err := collection.InsertOne(context.TODO(), user)
			if err != nil {
				http.Error(w, "Internal server error", http.StatusInternalServerError)
				return
			}
		} else {
			http.Error(w, "Internal server error", http.StatusInternalServerError)
			return
		}
	}

	// 更新挂机数据
	coins := int(time.Since(user.LastTime).Minutes()) * 10
	user.Coins += coins
	user.LastTime = time.Now()

	update := bson.M{"$set": bson.M{"coins": user.Coins, "lastTime": user.LastTime}}
	_, err = collection.UpdateOne(context.TODO(), filter, update)
	if err != nil {
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}

	// 返回用户金币数量
	type Response struct {
		Username string `json:"username"`
		Coins    int    `json:"coins"`
	}

	response := Response{
		Username: user.Name,
		Coins:    user.Coins,
	}

	jsonResponse, err := json.Marshal(response)
	if err != nil {
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(jsonResponse)
}

func InitRouter() *mux.Router {
	router := mux.NewRouter()

	router.HandleFunc("/guaji", GetCoinsHandler)

	return router
}
